// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// D [author] rhyme_lph
// l [email]  rhymelph@gmail.com
// y [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/account_dashboard_entity.dart';
import 'package:finance_app/src/entities/account_entity.dart';
import 'package:finance_app/src/entities/payment_entity.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/transaction_type_utils.dart';
import 'package:finance_app/src/widgets/button/add_button.dart';
import 'package:finance_app/src/widgets/button/assistant_button.dart';
import 'package:finance_app/src/widgets/button/balance_choose_button.dart';
import 'package:finance_app/src/widgets/button/normal_down_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_svg_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/chart/normal_sector_chart.dart';
import 'package:finance_app/src/widgets/chip/normal_chip.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_item.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_title_item.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/bank/cash_and_bank_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter_svg/svg.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

@RouterMeta(paramName: "cashAndBankPage")
class CashAndBankPage extends StatefulWidget {
  @override
  _CashAndBankPageState createState() => _CashAndBankPageState();
}

class _CashAndBankPageState extends State<CashAndBankPage>
    with PagePresenter<CashAndBankPage, CashAndBankProvider> {
  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        titleWidget: listBuilder<String>(
            builder: (BuildContext context, String value, Widget child) =>
                value.isEmpty ? Container() : _buildAccountSelectWidget(value),
            selector: (_, __) => __.getAccountName()),
        automaticallyImplyLeading: true,
        actions: [
          AssistantButton(
            entryPoint: "Cash & Bank",
          ),
          listBuilder<bool>(
            selector: (_, __) => __.currentAccount != null,
            builder: (BuildContext context, bool value, Widget child) =>
                Visibility(
                    visible: value,
                    replacement: SizedBox(),
                    child: listBuilder<List<String>>(
                      selector: (_, __) => List.from(__.menuList),
                      builder: (BuildContext context, List<String> value,
                              Widget child) =>
                          NormalMorePopupButton(
                        horizontalPadding: getDp(15),
                        onSelect: provider.onSelectMenu,
                        menuList: value,
                      ),
                    )),
          ),
        ],
      );

  @override
  Widget get buildWidget => listBuilder<bool>(
        selector: (_, __) => __.buttonBarIsUp,
        builder: (BuildContext context, bool value, Widget child) => Stack(
          children: [
            child,
            _buildBottomButton(value),
            // _buildTop(),
          ],
        ),
        child: _buildRecordList(),
      );

  Widget _buildSectorChart() {
    return listBuilder<AccountDashboardEntity>(
      selector: (_, __) => __.accountDashboard,
      builder:
          (BuildContext context, AccountDashboardEntity value, Widget child) =>
              value != null
                  ? Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal: getDp(50), vertical: getDp(18)),
                      child: NormalSectorChart(
                        incoming: value.incoming,
                        incomingAmount: value.incomingAmount,
                        outgoing: value.outgoing,
                        outgoingAmount: value.outgoingAmount,
                      ),
                    )
                  : Container(),
    );
  }

  Widget _buildBottomButton(bool isTop) => AnimatedPositioned(
      duration: Duration(milliseconds: 300),
      left: 0.0,
      right: 0.0,
      bottom: isTop
          ? MediaQuery.of(context).padding.bottom + getDp(40)
          : -getDp(60),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          NormalFloatSvgButton(
            onTap: provider.onAdd,
            asset: A.assetsImagesDashboardAdd,
          ),
        ],
      ));

  Widget _buildAllAccount() {
    return listBuilder<int>(
      selector: (_, __) => __.data?.length ?? 0,
      builder: (BuildContext context, int value, Widget child) => Column(
        children: List.generate(
            value,
            (index) => listBuilder<AccountEntity>(
                builder: (BuildContext context, AccountEntity value,
                        Widget child) =>
                    Padding(
                      padding: EdgeInsets.only(top: getDp(20)),
                      child: BalanceChooseButton(
                        title: '${value.bankName} ${value.accountNumber ?? ''}',
                        onTap:
                            //  value.accountNumber == null
                            //     ? null
                            //     :
                            () => provider.onNavBankDetail(value),
                        number:
                            '${value.currencyCode} ${CashUtils.formatCashAmount(value.balance)}',
                        numberColor: aceGrayColor,
                        borderColor: aceGrayColor,
                      ),
                    ),
                selector: (_, __) => __.data[index])),
      ),
    );
  }

  Widget _buildAccountSelectWidget(String value) {
    return PressedOpacityButton(
        onPressed: provider.onChangeAccount,
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
                constraints: BoxConstraints(
                  maxWidth: getDp(160),
                ),
                child: Text(
                  value,
                  maxLines: 1,
                )),
            SizedBox(
              width: getDp(10),
            ),
            Image.asset(
              A.assetsImagesStyleArrow,
              width: getDp(12),
              height: getDp(9),
            ),
          ],
        ));
  }

  Widget _buildTimeSelect() {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalDownButton(
              title: value,
              onTap: provider.onSelectTime,
            ),
        selector: (_, __) => __.currentSelectTime);
  }

  Widget _buildPaymentListWidget(Map<String, List<PaymentEntity>> map) {
    List<Widget> children = [];
    bool isFirst = true;
    for (final item in map.entries) {
      children.add(TransactionRecordTitleItem(
        title: item.key,
        topPadding: isFirst ? 0 : getDp(30),
        trailing: isFirst
            ? PressedOpacityButton(
                onPressed: provider.onNavViewAll,
                padding: EdgeInsets.symmetric(horizontal: getDp(20)),
                child: Text(
                  S.current.view_all,
                  style: TextStyle(
                    color: aceBlueColor,
                    fontSize: getSp(16),
                    fontWeight: FontWeight.w700,
                    height: 14 / 16,
                  ),
                ),
              )
            : null,
      ));
      children.addAll(List.generate(
          item.value.length,
          (index) => listBuilder<PaymentEntity>(
                selector: (_, __) => item.value[index],
                builder: (BuildContext context, PaymentEntity e, Widget child) {
                  return TransactionRecordItem(
                    onTap: () => provider.onNavPayment(e),
                    tag: TransactionTypeUtils.getTransactionType(
                        e.type == 'transfer'
                            ? '${e.type}_${e.flowType}'
                            : e.flowType),
                    name: e.name ?? '',
                    currencyCode: e.currencyCode,
                    time: '${DateTimeUtils.formatDateTimeString(e.issuedAt)}',
                    amount: e.total?.toDouble(),
                  );
                },
              )));
      isFirst = false;
    }
    return Column(
      children: children,
    );
  }

  Widget _buildRecordList() => ColoredBox(
        color: Colors.white,
        child: SmartRefresher(
          onRefresh: provider.onRefreshData,
          controller: provider.refreshController,
          child: ListView(
            controller: provider.controller,
            children: [
              listBuilder<AccountEntity>(
                selector: (_, __) => __.currentAccount,
                builder:
                    (BuildContext context, AccountEntity value, Widget child) =>
                        value == null
                            ? _buildAllAccount()
                            : Padding(
                                padding: EdgeInsets.only(top: getDp(20)),
                                child: BalanceChooseButton(
                                  title:
                                      '${value.bankName} ${value.accountNumber ?? ''}',
                                  onTap: null,
                                  number:
                                      '${value.currencyCode} ${CashUtils.formatCashAmount(value.balance)}',
                                  numberColor: aceGrayColor,
                                  borderColor: aceGrayColor,
                                ),
                              ),
              ),
              listBuilder<bool>(
                selector: (_, __) => __.currentAccount == null,
                builder: (BuildContext context, bool value, Widget child) =>
                    Visibility(
                  visible: value,
                  replacement: SizedBox(
                    height: getDp(20),
                  ),
                  child: NormalFormWrapper(
                    leftPadding: getDp(24),
                    child: AddButton(
                      title: S.current.add_bank_account,
                      onTap: provider.onNavAddBank,
                    ),
                  ),
                ),
              ),
              ListHeaderItem(
                title: S.current.overview,
              ),
              AppSpaces.h20,
              Row(
                children: [
                  _buildTimeSelect(),
                  Expanded(
                      child: listBuilder<String>(
                    selector: (_, __) => __.rangeTime,
                    builder:
                        (BuildContext context, String value, Widget child) =>
                            value != null
                                ? Align(
                                    alignment: Alignment.centerLeft,
                                    child: NormalChip(
                                      title: value,
                                      onClose: provider.onClearRangeTime,
                                    ),
                                  )
                                : Container(),
                  )),
                ],
              ),
              _buildSectorChart(),
              listBuilder<Map<String, List<PaymentEntity>>>(
                selector: (_, __) => Map.from(__.groupMap),
                builder: (BuildContext context,
                        Map<String, List<PaymentEntity>> value, Widget child) =>
                    LoadDataWidget<Map<String, List<PaymentEntity>>>(
                  value: value,
                  buildWidget: _buildPaymentListWidget,
                  isShowEmptyWidget: true,
                ),
              ),
            ],
          ),
        ),
      );
}
